package com.shop.utils;

import java.io.Writer;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class XmlCDATAUtils {

	private static XStream xstream = new XStream(new XppDriver(new NoNameCoder()) {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 取消对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;

				@SuppressWarnings("rawtypes")
				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}
				
				@Override
                public String encodeNode(String name) {
                    return name;
                }

				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});
	
	/**
	 * 
	* @Title: javaObject2Xml
	* @Description: Java对象转xml对象
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String javaObject2Xml(Object obj,String alias){
		xstream.alias(alias, obj.getClass());
		return xstream.toXML(obj);
	}
	
	/**
	 * 
	* @Title: xml2JavaObject
	* @Description: xml 转 java
	* @param @param xml
	* @param @param alias
	* @param @param obj
	* @param @return    设定文件
	* @return Object    返回类型
	* @throws
	 */
	@SuppressWarnings("rawtypes")
	public static Object xml2JavaObject(String xml,String alias,Object obj){
		xstream.alias(alias, (Class) obj);
		obj  = xstream.fromXML(xml);
		return obj;
	}

}
